package com.sicnu.cheer.leaugebar.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.sicnu.cheer.generalmodule.adapter.base.CommonAdapter;
import com.sicnu.cheer.generalmodule.adapter.viewholder.CommonViewHolder;
import com.sicnu.cheer.generalmodule.bean.EventBean;
import com.sicnu.cheer.generalmodule.fragment.base.BaseFragment;
import com.sicnu.cheer.generalmodule.util.DateUtil;
import com.sicnu.cheer.generalmodule.util.NetWorkUtil;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.generalmodule.widget.NoDoubleClickListener;
import com.sicnu.cheer.leaugebar.R;
import com.sicnu.cheer.leaugebar.eventmodule.activity.EventDetailActivity;
import com.sicnu.cheer.xlistview.view.XListView;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by cheer on 2017/1/24.
 * 最新活动热门活动子布局
 */

public class EventChildFragment extends BaseFragment {
    private LinearLayout noResultLL;
    private XListView listView;
    private CommonAdapter mAdapter;
    private List<EventBean> eventList;
    private ProgressDialog progressDialog;
    private int pageSize = 10;
    private int skip = 0;
    private boolean isHot;//是否是热门活动

    private List<BmobObject> outdateEvent;//过期的活动，设置为两天之后过期


    private RelativeLayout searchRL;
    private LinearLayout hideWhenFocusLayout;
    private EditText search;
    private ImageView showWhenFocus;
    private String searchInfo;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.layout_fragment_event;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);
        if (arguments != null) {
            isHot = arguments.getBoolean("isHot");
        }
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage("加载中...");
        outdateEvent = new ArrayList<>();
    }

    /**
     * 从Bmob后端云获取数据填充到界面
     *
     * @param isRefresh
     */
    public void requestDataFromBmob(final boolean isRefresh) {
        resetState();
        if (!NetWorkUtil.isConnect(mActivity)) {
            UIHelper.ToastMessage(mActivity, "没有网络，请设置网络");
            return;
        }
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        findEvent(isRefresh);

    }

    /**
     * 查询活动
     *
     * @param isRefresh 是否刷新
     */
    private void findEvent(final boolean isRefresh) {
        BmobQuery<EventBean> query = new BmobQuery<EventBean>();
        query.setLimit(pageSize);
        query.setSkip(skip);
        if (isHot) {
            query.order("-views");
        } else {
            query.order("-createdAt");
        }
        query.include("author,league");
        if (!StringUtils.isEmpty(searchInfo)) {
            query.addWhereContains("title", searchInfo);
        }
        query.findObjects(mActivity, new FindListener<EventBean>() {
            @Override
            public void onSuccess(List<EventBean> object) {
                if (object == null || object.size() == 0) {
                    setNoResultState(isRefresh);
                    stopXListView(isRefresh);
                } else {
                    if (isRefresh) {
                        eventList.clear();
                    }
                    changeStateIfNeeded(isRefresh, object);
                }
            }

            @Override
            public void onError(int code, String msg) {
                stopXListView(isRefresh);
                UIHelper.ToastMessage(mActivity, "查询失败：" + msg);
            }
        });
    }

    /**
     * 判断活动是否过期，是否需要改变活动状态
     *
     * @param isRefresh 是否是刷新状态
     * @param object    查询到的活动
     */
    private void changeStateIfNeeded(final boolean isRefresh, final List<EventBean> object) {
        for (int i = 0; i < object.size(); i++) {
            if (DateUtil.isThreeDaysAgo(object.get(i).getCreatedAt())) {
                object.get(i).setOn(false);
                outdateEvent.add(object.get(i));
            }
        }
        new BmobObject().updateBatch(mActivity, outdateEvent, new UpdateListener() {
            @Override
            public void onSuccess() {
                stopXListView(isRefresh);
                eventList.addAll(object);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(int code, String msg) {
                stopXListView(isRefresh);
                Log.d("update patch error", "onFailure: 批量更新失败:" + msg);
            }
        });
    }

    private void stopXListView(boolean isRefresh) {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (isRefresh) {
            listView.stopRefresh();
        } else {
            listView.stopLoadMore();
        }
    }

    private void resetState() {
        noResultLL.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
        listView.setPullLoadEnable(true);
    }

    private void setNoResultState(boolean isRefresh) {
        if (isRefresh) {
            noResultLL.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        } else {
            listView.setPullLoadEnable(false);
            UIHelper.ToastMessage(mActivity, "没有更多数据了");
        }
    }

    @Override
    protected void initView() {
        eventList = new ArrayList<>();
        noResultLL = (findViewById(com.sicnu.cheer.leaugebar.managemodule.R.id.no_data_ll));
        noResultLL.setVisibility(View.GONE);
        listView = findViewById(R.id.data_xlv);
        listView.setDividerHeight(0);
        //API21以上才有效果----第二种方式，比较简便
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            listView.setNestedScrollingEnabled(true);
        }
        setXListView();

        //请求服务器上的数据
        requestDataFromBmob(false);

        //将获取到的数据填充界面
        listView.setAdapter(mAdapter = new CommonAdapter<EventBean>(
                mActivity.getApplicationContext(), eventList, R.layout.item_event) {
            @Override
            public void convert(CommonViewHolder helper, EventBean item) {
                if (item != null) {
                    helper.setImageResource(R.id.event_state_icon_iv, item.getOn() ? R.mipmap.on_going : R.mipmap.finish);
                    helper.setText(R.id.event_title_tv, item.getTitle());
                    helper.setText(R.id.event_content_tv, item.getContent());
                    helper.setText(R.id.event_views_tv, String.valueOf(item.getViews()));
                    try {
                        String likes = String.valueOf(item.getLikesInt());
                        helper.setText(R.id.event_likes_tv,likes );
                    } catch (Exception e) {
                        helper.setText(R.id.event_likes_tv, "0");
                        e.printStackTrace();
                    }
                    helper.setImageByUrl(R.id.event_organizer_iv, item.getLeague().getLogo(), R.mipmap.default_logo);
                }
            }

        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), EventDetailActivity.class);
                intent.putExtra("event", eventList.get(position - 1));
                startActivity(intent);
            }
        });
        //监听编辑框的焦点改变事件
        showWhenFocus = findViewById(R.id.show_when_focus_iv);
        showWhenFocus.setVisibility(View.GONE);
        showWhenFocus.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                super.onNoDoubleClick(v);
                searchInfo=search.getText().toString().trim();
                requestDataFromBmob(true);
                hideSoftKeyboard(search, mActivity);
            }
        });
        searchRL = findViewById(R.id.search_rl);
        searchRL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search.setVisibility(View.VISIBLE);
                search.requestFocus();
            }
        });
        //当编辑框获取到焦点，则隐藏这个layout
        hideWhenFocusLayout = findViewById(R.id.search_hide_when_focus);
        search = findViewById(R.id.search_et);
        search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    hideWhenFocusLayout.setVisibility(View.GONE);
                    showWhenFocus.setVisibility(View.VISIBLE);
                    showSoftKeyboard(search, mActivity);
                } else {
                    hideWhenFocusLayout.setVisibility(View.VISIBLE);
                    showWhenFocus.setVisibility(View.GONE);
                    hideSoftKeyboard(search, mActivity);
                }
            }
        });
    }

    private void setXListView() {
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageSize = 10;
                skip = 0;
                requestDataFromBmob(true);
            }

            @Override
            public void onLoadMore() {
                pageSize += 10;
                skip += 10;
                requestDataFromBmob(false);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        requestDataFromBmob(true);
    }

    ///////////////////////////////////////// 隐藏或显示软键盘 /////////////////////////////////
    public static void hideSoftKeyboard(EditText editText, Context context) {
        if (editText != null && context != null) {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }

    public static void showSoftKeyboard(EditText editText, Context context) {
        if (editText != null && context != null) {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, 0);
        }
    }
}
